package com.atguigu.srb.gateway.filter;

import com.atguigu.common.utils.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class MyAutoFilter implements GlobalFilter {
    @Override
    public Mono<Void>
    filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().toString();
        String path = request.getPath().toString();
        List<String> tokens = request.getHeaders().get("token");
        if (null!=tokens&&tokens.size()>0){
            String token = tokens.get(0);
            if (!StringUtils.isEmpty(token)){
                boolean b = JwtUtils.checkToken(token);
                if (b){
                    String userId = JwtUtils.getUserId(token).toString();
                    request.mutate().header("userId",userId);
                    exchange.mutate().request(request);
                }
            }

        }
        return chain.filter(exchange);
    }
}
